import { Stomp } from '@stomp/stompjs';
import SockJS from 'sockjs-client';

const SOCKET_URL = 'http://localhost:9999/api/ws'; // 后端 WebSocket 端点

class WebSocketService {
    stompClient;

    connect(onConnectedCallback) {
        const socket = new SockJS(SOCKET_URL);
        this.stompClient = Stomp.over(socket);
        
        this.stompClient.connect({}, (frame) => {
            console.log('Connected to WebSocket:', frame);
            if (onConnectedCallback) {
                onConnectedCallback();
            }
        });
    }

    disconnect() {
        if (this.stompClient) {
            this.stompClient.disconnect();
        }
    }

    subscribe(topic, callback) {
        if (this.stompClient && this.stompClient.connected) {
            return this.stompClient.subscribe(topic, (message) => {
                callback(JSON.parse(message.body));
            });
        }
    }
}

export default new WebSocketService();